<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
            <!-- 选择商品分类 -->
            <el-row class="toprow">
                <el-col>
                    <span>请选择商品分类:</span>
                    <el-cascader
                        v-model="selectKeys"
                        :options="cateList"
                        :props="cateProps"
                        @change="handleChange"
                        :clearable="true"
                        style="width:250px"
                    ></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="tabsClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button
                        type="primary"
                        :disabled="isButtonDisabled"
                        @click="showAddParamDialog"
                    >添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="dongtaiParams" stripe border>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染Tag标签 -->
                                <el-tag
                                    closable
                                    v-for="(item,i) in scope.row.attr_vals"
                                    :key="i"
                                    @close="tagClose(i,scope.row)"
                                >{{item}}</el-tag>
                                <!-- input 添加属性值 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    @keyup.enter.native="inputSubmit(scope.row)"
                                    @blur="inputSubmit(scope.row)"
                                    ref="saveTagInput"
                                ></el-input>
                                <el-button
                                    class="button-new-tag"
                                    v-else
                                    @click="showInput(scope.row)"
                                    size="small"
                                >添加新属性</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="primary"
                                    icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)"
                                >编辑</el-button>
                                <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="deleteParam(scope.row.attr_id)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button
                        type="primary"
                        :disabled="isButtonDisabled"
                        @click="showAddParamDialog"
                    >添加属性</el-button>
                    <el-table :data="jingtaiParams" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染Tag标签 -->
                                <el-tag
                                    closable
                                    v-for="(item,i) in scope.row.attr_vals"
                                    :key="i"
                                    @close="tagClose(i,scope.row)"
                                >{{item}}</el-tag>
                                <!-- input 添加属性值 -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    @keyup.enter.native="inputSubmit(scope.row)"
                                    @blur="inputSubmit(scope.row)"
                                    ref="saveTagInput"
                                ></el-input>
                                <el-button
                                    class="button-new-tag"
                                    v-else
                                    @click="showInput(scope.row)"
                                    size="small"
                                >添加新属性</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    type="primary"
                                    icon="el-icon-edit"
                                    @click="showEditDialog(scope.row.attr_id)"
                                >编辑</el-button>
                                <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="deleteParam(scope.row.attr_id)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态参数窗口 -->
        <el-dialog
            title="提示"
            :visible.sync="addParamsDialogVisible"
            width="50%"
            @close="addDialogClosed"
        >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addFormSubmit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数或属性对话框 -->
        <el-dialog
            :title="'修改'+titleText"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editDialogClosed"
        >
            <!-- 修改表单 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParamsSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectKeys: [],
            cateList: [],
            cateProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover'
            },
            activeName: 'many',
            dongtaiParams: [],
            jingtaiParams: [],
            addParamsDialogVisible: false,
            addForm: {
                attr_name: ''
            },
            addFormRules: {
                attr_name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            },
            editDialogVisible: false,
            editForm: {
                attr_name: ''
            },
            editFormRules: {
                attr_name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        async getCateList() {
            const { data: res } = await this.$http.get('categories', {
                params: { type: 3 }
            })
            if (res.meta.status !== 200) {
                return this.$message.error('获取列表失败')
            }
            this.cateList = res.data
        },
        //当级联选择器中的值发生改变时触发
        async handleChange() {
            //console.log(this.selectKeys)
            if (this.selectKeys.length !== 3) {
                this.dongtaiParams = []
                this.jingtaiParams = []
                this.selectKeys = []
                return
            }
            const { data: res } = await this.$http.get(
                `categories/${this.cateId}/attributes`,
                {
                    params: { sel: this.activeName }
                }
            )
            if (res.meta.status !== 200) {
                return this.$$message.error('获取动态参数列表失败')
            }
            res.data.forEach((item) => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                // 添加额外的属性，控制文本框的显示与隐藏
                item.inputVisible = false
                // 文本框中输入的值
                item.inputValue = ''
            })

            if (this.activeName === 'many') {
                this.dongtaiParams = res.data
            } else if (this.activeName === 'only') {
                this.jingtaiParams = res.data
            }
        },
        tabsClick() {
            this.handleChange()
        },
        showAddParamDialog() {
            this.addParamsDialogVisible = true
        },
        addFormSubmit() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (!valid) {
                    return this.$message.error('请填写正确参数')
                }
                const { data: res } = await this.$http.post(
                    `categories/${this.cateId}/attributes`,
                    {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName,
                        attr_vals: ''
                    }
                )
                if (res.meta.status !== 201) {
                    return this.$message.error('添加' + this.titleText + '失败')
                }
                this.$message.success('添加成功')
                this.addParamsDialogVisible = false
                this.handleChange()
            })
        },
        addDialogClosed() {
            this.$refs.addFormRef.resetFields()
        },
        async showEditDialog(attr_id) {
            const {
                data: res
            } = await this.$http.get(
                `categories/${this.cateId}/attributes/${attr_id}`,
                { params: { attr_sel: this.activeName } }
            )
            console.log(attr_id)
            if (res.meta.status !== 200) {
                return this.$message.error('数据获取失败')
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        editParamsSubmit() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (!valid) {
                    return this.$message.error('请填写规范信息')
                }
                const { data: res } = await this.$http.put(
                    `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                    {
                        attr_name: this.editForm.attr_name,
                        attr_sel: this.activeName
                    }
                )
                console.log(res)
                if (res.meta.status !== 200) {
                    return this.$message.error('修改数据失败')
                }
                this.$message.success('修改数据成功')
                this.handleChange()
                this.editDialogVisible = false
            })
        },
        async deleteParam(attr_id) {
            const confirmResult = await this.$confirm(
                '您确定要删除吗, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch((cth) => {
                cth
            })
            if (confirmResult !== 'confirm') {
                return this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            }
            const { data: res } = await this.$http.delete(
                `categories/${this.cateId}/attributes/${attr_id}`
            )
            //console.log(attr_id)
            if (res.meta.status !== 200) {
                return this.$message.error('删除失败')
            }
            this.$message.success('删除成功')
            this.handleChange()
        },
        inputSubmit(row) {
            if (row.inputValue.trim().length === 0) {
                ;(row.inputValue = ''), (row.inputVisible = false)
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false
            this.saveAttrVals(row)
        },
        showInput(row) {
            row.inputVisible = true
            this.$nextTick(() => {
                this.$refs.saveTagInput.$refs.input.focus()
            })
        },
        async saveAttrVals(row) {
            const { data: res } = await this.$http.put(
                `categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
            )
            if (res.meta.status !== 200) {
                return this.$message.error('修改失败')
            }
            //this.$message.success('添加成功')
        },
        tagClose(index, row) {
            row.attr_vals.splice(index, 1)
            this.saveAttrVals(row)
        }
    },
    computed: {
        isButtonDisabled() {
            return this.selectKeys.length === 3 ? false : true
        },
        cateId() {
            if (this.selectKeys.length === 3) {
                return this.selectKeys[this.selectKeys.length - 1]
            }
            return null
        },
        titleText() {
            if (this.activeName === 'many') {
                return '动态参数'
            }
            return '静态属性'
        }
    }
}
</script>

<style lang='less' scoped>
.toprow {
    margin-top: 15px;
    span {
        margin-right: 10px;
    }
}
.el-tabs {
    margin-top: 10px;
}
.el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 120px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>